package cn.chencaiju.mysql.day03;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class JdbcTest {
	Connection connection=null;
	PreparedStatement prepareStatement;
	ResultSet executeQuery;
	@Before public void initlized() throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		String password="123456";
		String user="root";
		String url="jdbc:mysql://localhost:3306/employees";
		connection = DriverManager.getConnection(url, user, password);
		
	}
	@Test public void testJdbc() throws SQLException {
		// 参数化查询，对特殊字符进行转义，避免sql注入的问题
//		prepareStatement  = connection.prepareStatement("select * from user where name='zhangsan' or '1=1' and password='12345'");
		prepareStatement=connection.prepareStatement("select * from user where name=? and password=?");
		prepareStatement.setString(1,"zhangsan' or '1=1'");
		prepareStatement.setString(2, "12345");
//		System.out.println(prepareStatement.toString());
		executeQuery = prepareStatement.executeQuery();
		while(executeQuery.next()) {
//			System.out.println(executeQuery.getInt(1)+"\t"+executeQuery.getString(3)+"\t"+executeQuery.getString(4));
			System.out.println(executeQuery.getInt(1)+"\t"+executeQuery.getString(2));
		}
	}
	@After public void testClear() {
		clear(executeQuery);
		clear(prepareStatement);
		clear(connection);
	}
	
	public static void clear(AutoCloseable closeable) {
		if(closeable!=null) {
			try {
				closeable.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
}
